package com.dcits.mvc.common.service;

import java.util.Date;
import java.util.List;

import com.dcits.mvc.common.model.ServerInfo;
import com.dcits.tool.StringUtils;

public class ServerInfoService {
	
	private static final ServerInfo dao = new ServerInfo().dao();
	
	public void edit(ServerInfo serverInfo) {
		if (serverInfo.getId() == null) {
			serverInfo.setCreateTime(new Date());
			serverInfo.save();
		} else {
			serverInfo.update();
		}
	}
	
	public ServerInfo checkRepeat(ServerInfo serverInfo) {
		String sql = "select * from " + ServerInfo.TABLE_NAME + " where " + ServerInfo.column_host + "="
				+ "? and " + ServerInfo.column_port + "=? and " + ServerInfo.column_username + "=?";
		if (serverInfo.getId() != null) {
			sql += " and " + ServerInfo.column_id + "<>?";
			return dao.findFirst(sql, serverInfo.getHost(), serverInfo.getPort(), serverInfo.getUsername(), serverInfo.getId());
		} else {
			return dao.findFirst(sql, serverInfo.getHost(), serverInfo.getPort(), serverInfo.getUsername());
		}
	}
	
	public List<ServerInfo> listAll(String serverType) {
		String sql = "select * from " + ServerInfo.TABLE_NAME;
		if (StringUtils.isNotEmpty(serverType)) {
			sql += " where serverType='" + serverType + "'";
		}
		return dao.find(sql);
	}
	
	public ServerInfo findById(int id) {
		return dao.findById(id);
	}
	
	public void deleteById(int id) {
		dao.deleteById(id);
	}
	
	public void batchDelete(String ids) {
		for (String id:ids.split(",")) {
			deleteById(Integer.parseInt(id));
		}
	}
	
	public void updateLastTime(ServerInfo info) {
		info.set(ServerInfo.column_last_usetime, new Date()).update();
	}
}
